<?php
include('../resource/db/db.php');

if (!isset($_COOKIE['user_id'])) {
    header("Location: ../main/login.php");
    exit();
}

$user_id = $_COOKIE['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $avatar = $_FILES['avatar'];

    // 处理头像上传
    if ($avatar['error'] === UPLOAD_ERR_OK) {
        $uploadDir = '../uploads/avatars/';
        $uploadFile = $uploadDir . basename($avatar['name']);
        if (move_uploaded_file($avatar['tmp_name'], $uploadFile)) {
            $avatarPath = $avatar['name'];
        }
    }

    // 更新用户信息
    $sql = "UPDATE users SET username=?, email=?, avatar=?, updated_at=NOW() WHERE user_id=? AND is_deleted=FALSE";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('sssi', $username, $email, $avatarPath, $user_id);

    if ($stmt->execute()) {
        echo "<p>个人信息更新成功！</p>";
        header("Location: center.php");
    } else {
        echo "<p>个人信息更新失败，请重试。</p>";
    }

    $stmt->close();
}
?>
